//
//  ViewControllerOfLogin.m
//  TheProjectName
//
//  Created by 张雪娇 on 16/5/21.
//  Copyright © 2016年 sunzhichao. All rights reserved.
//

#import "ViewControllerOfLogin.h"
#import "RegisterVC.h"
#import "MenuVC.h"
#import "AppDelegate.h"
#define MAIN_SCREEN [UIScreen mainScreen].bounds.size

#define COLOR [UIColor colorWithRed:0.52 green:0.35 blue:0.25 alpha:1.00]

#define COLOR_BACK [UIColor colorWithRed:0.96 green:0.92 blue:0.83 alpha:1.00]

typedef NS_ENUM(NSInteger, textFieldOfType)
{
    textFieldOfType_NONE,
    textFieldOfType_USER,
    textFieldOfType_PASS
}type;

@interface ViewControllerOfLogin () <UITextFieldDelegate>

@property (nonatomic, retain) UIImageView *imageViewOfLeftHand;
@property (nonatomic, retain) UIImageView *imageViewOfRightHand;

@property (nonatomic, retain) UIImageView *imageViewOfLeftArm;
@property (nonatomic, retain) UIImageView *imageViewOfRightArm;

@property (nonatomic, retain) UITextField *textFieldOfUser;
@property (nonatomic, retain) UITextField *textFieldOfPassword;

@property (nonatomic, retain) UIButton *buttonOfLogin;
@property (nonatomic, retain) UIButton *buttonOfRegister;

@property (nonatomic, retain) UIImage *image;
@property (nonatomic, retain) UIImageView *imageViewOfLeaf;

@end

@implementation ViewControllerOfLogin


- (void)viewWillAppear:(BOOL)animated
{
    self.buttonOfLogin.frame = CGRectMake(-500, 380 , 300, 40);
    
    self.buttonOfRegister.frame = CGRectMake(-500, 430 , 300, 40);
}

- (void)viewDidAppear:(BOOL)animated
{
    //弹性动画
    //damping:阻尼，范围0-1，阻尼越接近于0，弹性效果越明显
    //velocity:弹性复位的速度
    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionAllowUserInteraction  animations:^{
        self.buttonOfLogin.frame = CGRectMake(MAIN_SCREEN.width / 2.0 - 300 / 2.0, 380 , 300, 40);
    } completion:^(BOOL finished) {
    }];
    
    [UIView animateWithDuration:1 delay:0.5 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionAllowUserInteraction  animations:^{
        self.buttonOfRegister.frame = CGRectMake(MAIN_SCREEN.width / 2.0 - 300 / 2.0, 430 , 300, 40);
    } completion:^(BOOL finished) {
    }];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self leafAnimation];
    
    //    [self viewAnimation];
    
    [self createSubviews];
}

#pragma mark - UIView 动画
- (void)viewAnimation
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:2];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(handleStop)];
}

- (void)handleStop
{
    [UIView setAnimationDuration:0];
}

#pragma mark - 树叶动画
- (void)leafAnimation
{
    self.image = [UIImage imageNamed:@"leafOfOrange"];
    
    [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(handleLeft) userInfo:nil repeats:YES];
}

#pragma mark - 计时器方法
- (void)handleLeft
{
    self.imageViewOfLeaf = [[UIImageView alloc] initWithImage:self.image];
    [self.view addSubview:self.imageViewOfLeaf];
    
    // 设置透明度
    self.imageViewOfLeaf.alpha = 0.8;
    // 树叶的大小
    int size = arc4random() % 50;
    // 开始x坐标
    int  startX = round(arc4random() % 600);
    // 最终x坐标
    int finshX = round(arc4random() % 600);
    // 速度
    double speed = 1 / round(arc4random() % 100) + 1.0;
    
    //树叶开始的大小和位置
    self.imageViewOfLeaf.frame = CGRectMake(startX, -300.0, size, size);
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:10 * speed];
    
    // 树叶最后消失的坐标
    self.imageViewOfLeaf.frame = CGRectMake(finshX, 1000.0, size, size);
    
    [UIView setAnimationDidStopSelector:@selector(onAnimationComplete:finished:context:)];
    [UIView setAnimationDelegate:self];
    [UIView commitAnimations];
}

- (void)onAnimationComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
   
    [self.imageViewOfLeaf removeFromSuperview];
     self.imageViewOfLeaf = nil;
}

#pragma mark - create SubViews
- (void)createSubviews
{
    // 背景
    NSString *path = [[NSBundle mainBundle]pathForResource:@"tree"ofType:@"jpg"];
    
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    
    self.view.layer.contents = (id)image.CGImage;
    
    // 猫头鹰头视图
    UIImageView *imageViewOfHeard = [[UIImageView alloc] init];
    imageViewOfHeard.frame = CGRectMake(MAIN_SCREEN.width / 2.0 - 211 / 2.0, 100, 211, 109);
    imageViewOfHeard.image = [UIImage imageNamed:@"heard.png"];
    // 剪裁掉imageViewOfHeard以外的视图
    imageViewOfHeard.layer.masksToBounds = YES;
    [self.view addSubview:imageViewOfHeard];
    
    // 猫头鹰两条手臂视图,添加到imageViewOfHeard上
    self.imageViewOfLeftArm = [[UIImageView alloc] init];
    self.imageViewOfLeftArm.frame = CGRectMake(61 - 60, 90, 40, 65);
    self.imageViewOfLeftArm.image = [UIImage imageNamed:@"leftArm.png"];
    [imageViewOfHeard addSubview:self.imageViewOfLeftArm];
    
    self.imageViewOfRightArm = [[UIImageView alloc] init];
    self.imageViewOfRightArm.frame = CGRectMake(imageViewOfHeard.frame.size.width / 2.0 +  60, 90, 40, 65);
    self.imageViewOfRightArm.image = [UIImage imageNamed:@"rightArm.png"];
    [imageViewOfHeard addSubview:self.imageViewOfRightArm];
    
    // 注册视图
    UIView *viewOfLogin = [[UIView alloc] init];
    viewOfLogin.frame = CGRectMake(15, 200, MAIN_SCREEN.width - 30, 160);
    viewOfLogin.layer.borderWidth = 1.0f;
    viewOfLogin.layer.borderColor = COLOR.CGColor;
    viewOfLogin.layer.cornerRadius = 8.0f;
    viewOfLogin.backgroundColor = COLOR_BACK;
    viewOfLogin.alpha = 0.8f;
    [self.view addSubview:viewOfLogin];
    
    // 猫头鹰手(圆点)视图, 添加到self.view上, 刚好盖住手臂露出部分
    self.imageViewOfLeftHand = [[UIImageView alloc] init];
    self.imageViewOfLeftHand.frame = CGRectMake(MAIN_SCREEN.width / 2.0 - 100, viewOfLogin.frame.origin.y - 22, 40, 40);
    self.imageViewOfLeftHand.image = [UIImage imageNamed:@"leftHand.png"];
    [self.view addSubview:self.imageViewOfLeftHand];
    
    self.imageViewOfRightHand = [[UIImageView alloc] init];
    self.imageViewOfRightHand.frame = CGRectMake(MAIN_SCREEN.width / 2.0 + 62, viewOfLogin.frame.origin.y - 22, 40, 40);
    self.imageViewOfRightHand.image = [UIImage imageNamed:@"rightHand.png"];
    [self.view addSubview:self.imageViewOfRightHand];
    
    // 修改TextField的光标颜色
    [[UITextField appearance] setTintColor:COLOR];
    
    // 用户名textField
    self.textFieldOfUser = [[UITextField alloc] init];
    self.textFieldOfUser.frame = CGRectMake(30, 30, viewOfLogin.frame.size.width - 60, 44);
    self.textFieldOfUser.delegate = self;
    self.textFieldOfUser.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.textFieldOfUser.layer.cornerRadius = 8.0f;
    self.textFieldOfUser.layer.borderColor = COLOR.CGColor;
    self.textFieldOfUser.layer.borderWidth = 0.8f;
    self.textFieldOfUser.placeholder = @"请输入用户名";
    // 加入取消
    self.textFieldOfUser.clearButtonMode = UITextFieldViewModeAlways;
    // 修改用户名的placeholder的字体颜色
    NSMutableAttributedString *placeholderOfUser = [[NSMutableAttributedString alloc] initWithString:self.textFieldOfUser.placeholder];
    [placeholderOfUser addAttribute:NSForegroundColorAttributeName
                              value:COLOR
                              range:NSMakeRange(0, self.textFieldOfUser.placeholder.length)];
    self.textFieldOfUser.attributedPlaceholder = placeholderOfUser;
    // 加入取消
    self.textFieldOfPassword.clearButtonMode = UITextFieldViewModeAlways;
    // 用户名视图的左视图
    self.textFieldOfUser.leftView = [[UIView alloc] init];
    self.textFieldOfUser.leftView.frame = CGRectMake(0, 0, 44, 44);
    self.textFieldOfUser.leftViewMode = UITextFieldViewModeAlways;
    UIImageView *imageViewOfUser = [[UIImageView alloc] init];
    imageViewOfUser.frame = CGRectMake(11, 11, 22, 22);
    imageViewOfUser.image = [UIImage imageNamed:@"user"];
    
    [self.textFieldOfUser.leftView addSubview:imageViewOfUser];
    [viewOfLogin addSubview:self.textFieldOfUser];
    
    //密码textField
    self.textFieldOfPassword = [[UITextField alloc] init];
    self.textFieldOfPassword.frame = CGRectMake(30, 90, viewOfLogin.frame.size.width - 60, 44);
    self.textFieldOfPassword.delegate = self;
    self.textFieldOfPassword.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.textFieldOfPassword.layer.cornerRadius = 8.0f;
    self.textFieldOfPassword.layer.borderColor = COLOR.CGColor;
    self.textFieldOfPassword.layer.borderWidth = 0.8f;
    self.textFieldOfPassword.placeholder = @"请输入密码";
    // 修改placeholder的字体颜色
    NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc]initWithString:self.textFieldOfPassword.placeholder];
    [placeholder addAttribute:NSForegroundColorAttributeName
                        value:COLOR
                        range:NSMakeRange(0, self.textFieldOfPassword.placeholder.length)];
    self.textFieldOfPassword.attributedPlaceholder = placeholder;
    // 密码视图的左视图
    self.textFieldOfPassword.leftView = [[UIView alloc] init];
    self.textFieldOfPassword.leftView.frame = CGRectMake(0, 0, 44, 44);
    self.textFieldOfPassword.leftViewMode = UITextFieldViewModeAlways;
    UIImageView *imageViewOfPassword = [[UIImageView alloc] init];
    imageViewOfPassword.frame = CGRectMake(11, 11, 22, 22);
    imageViewOfPassword.image = [UIImage imageNamed:@"password"];
    self.textFieldOfPassword.secureTextEntry = YES;
    
    [self.textFieldOfPassword.leftView addSubview:imageViewOfPassword];
    [viewOfLogin addSubview:self.textFieldOfPassword];
    
    // 登录按钮
    self.buttonOfLogin = [UIButton buttonWithType:UIButtonTypeSystem];
    //    self.buttonOfLogin.frame = CGRectMake(MAIN_SCREEN.width / 2.0 - 300 / 2.0, 380 , 300, 40);
    self.buttonOfLogin.layer.masksToBounds = YES;
    self.buttonOfLogin.layer.borderWidth = 1.0f;
    self.buttonOfLogin.layer.borderColor = COLOR.CGColor;
    self.buttonOfLogin.layer.cornerRadius = 8.0f;
    [self.buttonOfLogin setTitle:@"登录" forState:UIControlStateNormal];
    [self.buttonOfLogin addTarget:self action:@selector(handleLogin:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.buttonOfLogin];
    self.buttonOfLogin.titleLabel.font = [UIFont systemFontOfSize:22];
    [self.buttonOfLogin setTitleColor:COLOR forState:UIControlStateNormal];
    
    // 注册按钮
    self.buttonOfRegister = [UIButton buttonWithType:UIButtonTypeSystem];
    //    self.buttonOfRegister.frame = CGRectMake(MAIN_SCREEN.width / 2.0 - 300 / 2.0, 430 , 300, 40);
    self.buttonOfRegister.layer.masksToBounds = YES;
    self.buttonOfRegister.layer.borderWidth = 1.0f;
    self.buttonOfRegister.layer.borderColor = COLOR.CGColor;
    self.buttonOfRegister.layer.cornerRadius = 8.0f;
    [self.buttonOfRegister setTitle:@"注册" forState:UIControlStateNormal];
    [self.buttonOfRegister addTarget:self action:@selector(handleRegister:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.buttonOfRegister];
    self.buttonOfRegister.titleLabel.font = [UIFont systemFontOfSize:22];
    [self.buttonOfRegister setTitleColor:COLOR forState:UIControlStateNormal];
}

#pragma mark - 登录按钮事件
- (void)handleLogin:(UIButton *)button
{
   
    // 判断用户名
    if (_textFieldOfUser.text.length == 0) {
        [self presentAlert:@"用户名不能为空" message:nil];
    }
    // 判断密码
    else if (_textFieldOfPassword.text.length == 0) {
        [self presentAlert:@"密码不能为空" message:nil];
    }
    else{
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  
            // 登录
            EMError *error = [[EMClient sharedClient] loginWithUsername:_textFieldOfUser.text password:_textFieldOfPassword.text];
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                if (!error) {
                    // 设置自动登录
                    [[EMClient sharedClient].options setIsAutoLogin:YES];
                    AppDelegate *appdelegate =[[UIApplication sharedApplication] delegate];
                    // 推出界面
                    [appdelegate resetLocker];
                    appdelegate.window.rootViewController = appdelegate.locker;
                   
                }
                else{
                    [self presentAlert:@"用户名或者密码错误" message: nil];
                }
                
            });
        });
        
      
    }
    
}


#pragma mark - 注册按钮事件
- (void)handleRegister:(UIButton *)button
{
    
    RegisterVC *vc = [[RegisterVC alloc]init];
    
    [self presentViewController:vc animated:YES
                     completion:^{
                         
                         // 修改页面推出方式
                         [vc setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
                     }];
    
}

#pragma mark - 点击空白处收键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.textFieldOfUser resignFirstResponder];
    [self.textFieldOfPassword resignFirstResponder];
}

#pragma mark - 当按return时的事件
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.textFieldOfPassword resignFirstResponder];
    [self.textFieldOfUser resignFirstResponder];
    return YES;
}

#pragma mark - textField Delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if ([textField isEqual:self.textFieldOfUser])
    {
        if (type != textFieldOfType_PASS)
        {
            type = textFieldOfType_USER;
            
            return;
        }
        type = textFieldOfType_USER;
        // 不蒙眼的状态
        [UIView animateWithDuration:0.5f animations:^{
            self.imageViewOfLeftArm.frame = CGRectMake(self.imageViewOfLeftArm.frame.origin.x - 60, self.imageViewOfLeftArm.frame.origin.y + 30, self.imageViewOfLeftArm.frame.size.width, self.imageViewOfLeftArm.frame.size.height);
            
            self.imageViewOfRightArm.frame = CGRectMake(self.imageViewOfRightArm.frame.origin.x + 48, self.imageViewOfRightArm.frame.origin.y + 30, self.imageViewOfRightArm.frame.size.width, self.imageViewOfRightArm.frame.size.height);
            
            self.imageViewOfLeftHand.frame = CGRectMake(self.imageViewOfLeftHand.frame.origin.x - 70, self.imageViewOfLeftHand.frame.origin.y, 40, 40);
            
            self.imageViewOfRightHand.frame = CGRectMake(self.imageViewOfRightHand.frame.origin.x + 30, self.imageViewOfRightHand.frame.origin.y, 40, 40);
        }];
    }
    else
    {
        if (type == textFieldOfType_PASS)
        {
            type = textFieldOfType_PASS;
            
            return;
        }
        
        type = textFieldOfType_PASS;
        
        // 蒙眼的状态
        [UIView animateWithDuration:0.5f animations:^{
            self.imageViewOfLeftArm.frame = CGRectMake(self.imageViewOfLeftArm.frame.origin.x + 60, self.imageViewOfLeftArm.frame.origin.y - 30, self.imageViewOfLeftArm.frame.size.width, self.imageViewOfLeftArm.frame.size.height);
            
            self.imageViewOfRightArm.frame = CGRectMake(self.imageViewOfRightArm.frame.origin.x - 48, self.imageViewOfRightArm.frame.origin.y - 30, self.imageViewOfRightArm.frame.size.width, self.imageViewOfRightArm.frame.size.height);
            
            self.imageViewOfLeftHand.frame = CGRectMake(self.imageViewOfLeftHand.frame.origin.x + 70, self.imageViewOfLeftHand.frame.origin.y, 0, 0);
            
            self.imageViewOfRightHand.frame = CGRectMake(self.imageViewOfRightHand.frame.origin.x - 30, self.imageViewOfRightHand.frame.origin.y, 0, 0);
        }];
    }
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 @brief 推出提示框
 
 @param title   标题
 @param message 信息
 */
- (void)presentAlert:(NSString *)title message:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:^{
        
    }];
    [self performSelector:@selector(dismiss:) withObject:alert afterDelay:2];
}
/**  Alert 消失 */
- (void)dismiss:(UIAlertController *)alert {
    [alert dismissViewControllerAnimated:YES completion:^{
        
    }];
}



/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
